package de.hoits.app.gewichtskontolle.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper
{
	private static final String TAG = "DatabaseHelper";
	
	private static final String SCHEMA_NAME = "hoits_applicationdata";
	private static final String TABLE_NAME = "gewicht"; 

	private static final int DATABASE_VERSION = 1;

	/**
	 * Konstruktor
	 * 
	 * @param context
	 */
	public DatabaseHelper(Context context)
	{
		super(context, SCHEMA_NAME, null, DATABASE_VERSION);
	}

	/**
	 * Method is called during creation of the database
	 */
	@Override
	public void onCreate(SQLiteDatabase database) 
	{
		Log.i(TAG, "creating database (" + TABLE_NAME + ")");
		
		database.execSQL(generateCreateSQL());
	}

	/**
	 *  Method is called during an upgrade of the database, e.g. if you increase the database version
	 */
	@Override
	public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) 
	{
		if (Log.isLoggable(TAG, Log.WARN))
		{
			Log.w(TAG, "Upgrading database (" + TABLE_NAME + ") from version " + oldVersion + " to " + 
					newVersion + ", which will destroy all old data");
		}
		
		database.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
		onCreate(database);
	}
	
	/**
	 * Erzeugt das SQL zur Datenbank generierung
	 * 
	 * @return
	 */
	private String generateCreateSQL()
	{
		final StringBuffer sb = new StringBuffer();
		sb.append("CREATE TABLE ");
		sb.append(TABLE_NAME);
		sb.append(" (id INTEGER  PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE ,");
		sb.append("  meinGewicht FLOAT NOT NULL ,");
		sb.append("  datum DATETIME NOT NULL  DEFAULT CURRENT_DATE,");
		sb.append("  description TEXT)");
		
		if (Log.isLoggable(TAG, Log.DEBUG))
		{
			Log.d(TAG, "SQL: " + sb.toString());
		}
		
		return sb.toString();
	}
}